package cn.edu.scau.cmi.suyaoxing.hibernate.dao;
import cn.edu.scau.cmi.suyaoxing.hibernate.domain.*;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.Query;

public class TeacherDAO implements ITeacherDAO{
	@Override
	public void save(Teacher teacher) {
				Configuration cfg = new Configuration();
				cfg.configure("/hibernate.cfg.xml");
				SessionFactory buildSessionFactory = cfg.buildSessionFactory();
				Session openSession = buildSessionFactory.openSession();
				openSession.beginTransaction();
				openSession.save(teacher);
				 openSession.getTransaction().commit();
				openSession.close();
				buildSessionFactory.close();
	}
	
	@Override
	public void delete(Teacher teacher) {
		Configuration cfg = new Configuration();
		cfg.configure("/hibernate.cfg.xml");
		SessionFactory buildSessionFactory = cfg.buildSessionFactory();
		Session openSession = buildSessionFactory.openSession();
		openSession.beginTransaction();
		openSession.delete(teacher);
		 openSession.getTransaction().commit();
		openSession.close();
		buildSessionFactory.close();
 
	}
	
	@Override
	public void update(Teacher teacher) {
		Configuration cfg = new Configuration();
		cfg.configure("/hibernate.cfg.xml");
		SessionFactory buildSessionFactory = cfg.buildSessionFactory();
		Session openSession = buildSessionFactory.openSession();
		openSession.beginTransaction();
		openSession.update(teacher);
		 openSession.getTransaction().commit();
		openSession.close();
		buildSessionFactory.close();
	}

	@Override
	public Teacher get(long id) {
		Configuration cfg = new Configuration();
		cfg.configure("/hibernate.cfg.xml");
		SessionFactory buildSessionFactory = cfg.buildSessionFactory();
		Session openSession = buildSessionFactory.openSession();
		Teacher teacher= (Teacher) openSession.get("cn.edu.scau.cmi.suyaoxing.hibernate.domain.Teacher",id);
		openSession.close();
		buildSessionFactory.close();
		return teacher;
	}
 
	@Override
	public List<Teacher> list() {
		Configuration cfg = new Configuration();
		cfg.configure("/hibernate.cfg.xml");
		SessionFactory buildSessionFactory = cfg.buildSessionFactory();
		Session openSession = buildSessionFactory.openSession();
		Query<Teacher> query = openSession.createSQLQuery("select * from teacher").addEntity(Teacher.class);
		List<Teacher> list = query.list();
		openSession.close();
		buildSessionFactory.close();
		return list;
		/*
		String queryString = "from Student";
		Query queryObject = openSession.createQuery(queryString);
		return queryObject.list();*/
	}
}
